<template>
	<!-- 滑块切换 -->
	<view class="slider-switch-container">
		<view class="active-modal" :style="{ left: leftOffset }"></view>
		<view
			class="switch-item flex-center"
			@click="handleSwitch('left')"
			:style="{ color: currentActive === 1 ? '#fff' : '#b3b3b3' }">
			{{ activeText }}
		</view>
		<view
			class="switch-item flex-center"
			@click="handleSwitch('right')"
			:style="{ color: currentActive === 2 ? '#fff' : '#b3b3b3' }">
			{{ inactiveText }}
		</view>
	</view>
</template>

<script>
import { defineComponent, computed } from 'vue';

export default defineComponent({
	name: 'SliderSwitch',
	props: {
		modelValue: {
			required: true,
		},
		activeText: {
			type: String,
			default: '打开',
		},
		inactiveText: {
			type: String,
			default: '关闭',
		},
		activeValue: { required: true },
		inactiveValue: { required: true },
	},
	emits: ['update:modelValue'],
	setup(props, { emit }) {
		// 当前激活的索引
		const currentActive = computed(() => {
			return props.modelValue === props.activeValue ? 1 : 2;
		});

		// 左侧偏移量
		const leftOffset = computed(() => {
			if (currentActive.value === 1) return '0';
			return '50%';
		});

		// 切换状态
		const handleSwitch = (behavior) => {
			if (behavior === 'left') {
				emit('update:modelValue', props.activeValue);
			} else {
				emit('update:modelValue', props.inactiveValue);
			}
		};

		return {
			leftOffset,
			currentActive,
			handleSwitch,
		};
	},
});
</script>

<style lang="scss" scoped>
// 滑块切换
.slider-switch-container {
	width: 186rpx;
	height: 56rpx;
	display: flex;
	position: relative;
	border-radius: 56rpx;
	background-color: #f6f6f6;

	.active-modal {
		left: 0;
		width: 93rpx;
		height: 56rpx;
		position: absolute;
		border-radius: 80rpx;
		transition: left 0.3s;
		background-color: $primary-color;
	}

	.switch-item {
		width: 50%;
		z-index: 30;
		height: 56rpx;
		color: #b3b3b3;
		font-size: 24rpx;
		overflow: hidden;
		position: relative;
		white-space: nowrap;
		transition: color 0.3s;
		text-overflow: ellipsis;
	}
}
</style>
